<div id="formDiv"></div>
<script type="text/html" id="settledDetailContent">
    <form lay-filter="settledDetailContentForm" id="settledDetailContentForm" class="layui-form open-form">
        <div class="open-model">
            <div class="open-auto">
                <table class="layui-table" id="lookDataForm" lay-filter="lookDataForm"></table>
                {{# if(d.eventName === 'process'){ }}
                <div class="layui-form-item tableContent" id="processCont" style="display: none;overflow: visible;">
                    <label class="layui-form-label" style="text-align: left">审核内容：</label>
                    <table class="layui-table" id="processFormTable" lay-filter="processFormTable"></table>
                </div>
                {{# } }}
                <div class="layui-form-item layui-row" id="continto" style="display: none">
                    <div style="width: calc(50% - 25px);float:left;">
                        <label class="layui-form-label" style="text-align: left">服务产品价格：</label>
                        <table class="layui-table" id="serviceProductsFormTable"
                               lay-filter="serviceProductsFormTable"></table>
                    </div>
                    <div style="margin-left: 50px;float: right;width: calc(50% - 25px);">
                        <label class="layui-form-label" style="text-align: left">托管费用设置：</label>
                        <table class="layui-table" id="custodyFeesFormTable"
                               lay-filter="custodyFeesFormTable"></table>
                    </div>
                </div>
                <div class="layui-form-item text-right">
                    <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">关闭</button>
                    <button class="layui-btn" lay-filter="formSubmit" type="button" lay-submit>提交</button>
                </div>
            </div>
        </div>
    </form>
</script>


<script>
    layui.use(["layer", "form", "table", "admin", "laydate", "upload", "laytpl"], async function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var admin = layui.admin;
        var upload = layui.upload;
        let laydate = layui.laydate;
        let laytpl = layui.laytpl;
        const nowData = {...parentData};
        let data = nowData?.data;
        var settledStatus = nowData.data[0].status
        let customerId
        try {
            if (!data.status) {
                nowData.status = 0
            } else {
                nowData.status = data.status
            }
        } catch (e) {
            nowData.status = 0
        }

        const receiptType = await admin.reqPro('enterprise/contract/admin/contractCategory/list?page=1&limit=9999', {});
        const receiptTypeList = receiptType.data
        const warehouseUser = await admin.reqPro("enterprise/sell/admin/contactInfo/list?page=1&limit=9999", {selCustomerId: data[0].warehouseCustomerId});
        warehouseUser.data.map(item => {
            if (item.id == nowData.data[0].contactId) {
                nowData.data[0].telephone = item.telephone
                nowData.data[0].email = item.email
            }
        })
        const warehouseUserList = warehouseUser.data;

        const contractorcont = await admin.reqPro('user/admin/user/list?limit=9999', {});
        const contractorList = contractorcont.data;

        let skuList = [];
        laytpl(settledDetailContent.innerHTML).render({...nowData}, function (html) {
            $("#formDiv").after(html);
        });

        table.render({
            elem: "#lookDataForm",
            page: false,
            limit: 999999,
            data: nowData.data,
            cols: [
                [
                    {
                        field: "settledOrder",
                        align: "center",
                        title: "申请单编号",
                        hide: nowData.eventName == "detail" ? false : true
                    },
                    {field: "factoryName", align: "center", title: "仓库编号"},
                    {field: "customerName", align: "center", title: "客户名称"},
                    {field: "warehouseCustomerId", align: "center", title: "客户编码"},
                    {field: "customerLevelId", align: "center", title: "客户级别"},
                    {field: "contactName", align: "center", title: "联系人"},
                    {field: "telephone", align: "center", title: "电话"},
                    {field: "email", align: "center", title: "邮箱"},
                    {field: "createTime", align: "center", title: "申请日期"},
                    {
                        field: "contractCode",
                        align: "center",
                        title: "合同编号",
                        hide: nowData.eventName == "detail" ? false : true
                    },
                    {
                        field: "effectiveDate",
                        align: "center",
                        title: "生效日期",
                        hide: nowData.eventName == "detail" ? false : true
                    },
                    {
                        field: "expiryDate",
                        align: "center",
                        title: "有效截止日期",
                        hide: nowData.eventName == "detail" ? false : true
                    },
                    {
                        field: "status", align: "center", title: "审核而结果",
                        templet: admin.setTableSelect(
                            "status",
                            [
                                {value: "1", label: "通过审核"},
                                {value: "2", label: "驳回审核"},
                            ], false, "status"
                        ), hide: nowData.eventName == "detail" ? true : false
                    },
                    {
                        field: "remark", align: "center", title: "备注"
                    },
                ]
            ],
            done: function (res, curr, count) {
                admin.tableSelectChange(
                    "lookDataForm",
                    "status",
                    (index, value, tableData, field, tableId) => {
                        let list = table.cache["processFormTable"];
                        let list1 = table.cache["serviceProductsFormTable"];
                        let list2 = table.cache["custodyFeesFormTable"];
                        console.log(value, "value")
                        if (value == 1) {
                            $("#processCont").show();
                            $("#continto").show();
                            if (list.length == 0) {
                                table.reload("processFormTable", {
                                    data: cot
                                });
                            } else {
                                table.reload("processFormTable", {
                                    data: list
                                });
                            }
                            table.reload("serviceProductsFormTable", {
                                data: list1
                            });
                            table.reload("custodyFeesFormTable", {
                                data: list2
                            });
                        } else {
                            $("#processCont").hide();
                            $("#continto").hide();
                        }
                        $("#processCont .layui-table-body").css("overflow", "visible");
                        $("#processCont .layui-table-box").css("overflow", "visible");
                        $("#processCont .layui-table-view").css("overflow", "visible");
                        settledStatus = value
                    }
                );

            }
        });

        const processFormVal = table.render({
            elem: "#processFormTable",
            page: false,
            limit: 999999,
            data: [],
            cols: [
                [
                    {
                        field: "type", align: "center", title: "合同类型",
                    },
                    {
                        field: "contractCode", align: "center", title: "合同编号",
                        templet: admin.setTableInput("contractCode", nowData.eventName == "detail", "contractCode")
                    },
                    {
                        field: "contractName",
                        align: "center",
                        title: "合同名称",
                        templet: admin.setTableInput("contractName", nowData.eventName == "detail", "contractName")
                    },
                    {
                        field: "contractCategoryId",
                        align: "center",
                        title: "合同分类",
                        templet: admin.setTableSelect("contractCategoryId",
                            receiptTypeList.map((v) => {
                                return {
                                    label: v.name,
                                    value: v.id
                                };
                            }), nowData.eventName === "detail", "contractCategoryId")
                    },
                    {
                        field: "warehouseUserId", align: "center", title: "客户签约人",
                        templet: admin.setTableSelect("warehouseUserId",
                            warehouseUserList.map((v) => {
                                return {
                                    label: v.name,
                                    value: v.id
                                };
                            }), nowData.eventName === "detail", "warehouseUserId")
                    },
                    {
                        field: "contractorId", align: "center", title: "我方签约人",
                        templet: admin.setTableSelect("contractorId", contractorList.map((v) => {
                            return {
                                label: v.nickname,
                                value: v.id
                            };
                        }), nowData.eventName === "detail", "contractorId")
                    },
                    {
                        field: "contractFileUrl", align: "center", title: "合同附件",
                        templet: admin.setTableUpload("contractFileUrl", nowData.eventName == "detail")
                    },
                    {
                        field: "effectiveDate", align: "center", title: "生效日期",
                        templet: admin.setTableInput('effectiveDate', nowData.eventName === 'recList', 'effectiveDate'),
                    },
                    {
                        field: "expiryDate", align: "center", title: "有效截止日期",
                        templet: admin.setTableInput('expiryDate', nowData.eventName === 'recList', 'expiryDate'),
                    },
                    {
                        field: "remark", align: "center", title: "备注信息",
                        templet: admin.setTableInput("remark", nowData.eventName == "detail", "remark")
                    },
                ]
            ],
            done: function () {
                admin.tableInputChange("processFormTable");
                admin.tableSelectChange("processFormTable", 'contractCategoryId');
                admin.tableSelectChange("processFormTable", 'warehouseUserId');
                admin.tableSelectChange("processFormTable", 'contractorId');
                // 上传图片
                upload.render({
                    elem: ".upload-btn", // 绑定上传按钮
                    url: config.upload_url + "uploadFile",
                    accept: "file", // 可接受的文件类型
                    headers: {Authorization: "Bearer " + config.getToken()},
                    done: function (res, index, upload) {
                        // 上传成功的回调
                        if (res.code === 200) {
                            // 更新表格缓存中的数据
                            const button = $(this.item);
                            const index = button.data("index");
                            let tableData = table.cache["processFormTable"];
                            let rowIndex = tableData.findIndex((v) => v["LAY_TABLE_INDEX"] == index);
                            if (rowIndex > -1) {
                                tableData[rowIndex].contractFileUrl = res.data.url; // 假设接口返回的文件路径是 res.data.fileUrl
                                tableData[rowIndex].contractFileUrlName = res.data.fileName; // 假设接口返回的文件路径是 res.data.fileUrl
                            }
                            $(`#uploaded-${index}`).html(`<a href="${res.data.url}" target="_blank">查看附件</a>`);
                            console.log("文件上传成功:", res.data);
                        } else {
                            console.error("文件上传失败:", res.message);
                        }
                    },
                    error: function () {
                        // 上传失败的回调
                        console.error("上传失败");
                    }
                });
                const expiryDate = document.querySelectorAll('.expiryDate');
                expiryDate.forEach((input, index) => {
                    laydate.render({
                        elem: input,
                        format: 'yyyy-MM-dd HH:mm:ss',
                        trigger: 'click',
                        done: function (value) {
                            input.value = value;
                            let tableData = table.cache['processFormTable'];
                            let rowIndex = tableData.findIndex((v) => v['LAY_TABLE_INDEX'] == index);
                            if (rowIndex > -1) {
                                tableData[rowIndex].expiryDate = value;
                            }
                        },
                    });
                });
                const effectiveDate = document.querySelectorAll('.effectiveDate');
                effectiveDate.forEach((input, index) => {
                    laydate.render({
                        elem: input,
                        format: 'yyyy-MM-dd HH:mm:ss',
                        trigger: 'click',
                        done: function (value) {
                            input.value = value;
                            let tableData = table.cache['processFormTable'];
                            let rowIndex = tableData.findIndex((v) => v['LAY_TABLE_INDEX'] == index);
                            if (rowIndex > -1) {
                                tableData[rowIndex].effectiveDate = value;
                            }
                        },
                    });
                });
            }
        });

        var stamp= new Date().getTime() + 8 * 60 * 60 * 1000;
        var beijingTime = new Date(stamp).toISOString().replace(/T/, '').replace(/-/g, '').replace(/:/g, '').replace(/\..+/, '').substring(0, 12);
        var today = new Date();
        var customerName = nowData.data[0]?.customerName+today.getFullYear();
        var cot = [{
            type: nowData.data[0].type,
            contractCode: beijingTime,
            contractName: customerName,
            contractCategoryId: "",
            warehouseUserId: "",
            contractorId: "",
            contractFileUrl: "",
            effectiveDate: "",
            expiryDate: "",
            remark: ""
        }]


        if (nowData.data[0].status == 1) {
            $("#processCont").show();
            $("#continto").show();
            table.reload("processFormTable", {
                data: cot
            });
        }


        /*服务产品价格*/
        let tableVal = table.render({
            elem: "#serviceProductsFormTable",
            // page: false,
            limit: 9999,
            height: 350,
            // url: config.base + 'warehouse/warehouse/feeItems/list',
            data: [],
            cols: [
                [
                    {field: "feeItemName", align: "center", title: "业务项目"},
                    {field: "remark", align: "center", title: "业务描述"},
                    {field: "price", align: "center", title: "标准价"},
                    {field: "memberPrice", align: "center", title: "会员价"},
                    {
                        field: "contractPrice", align: "center", title: "合同价格",
                        templet: admin.setTableInput("contractPrice", nowData.eventName === "detail", "contractPrice")
                    },
                ]
            ],
            done: function (res, curr, count) {
                admin.tableInputChangeByClass("serviceProductsFormTable", "contractPrice");
            },
            parseData: function (res) {
            },
        });

        /*托管费用设置*/
        const VarietyVal = table.render({
            elem: "#custodyFeesFormTable",
            page: false,
            limit: 9999,
            height: 350,
            // url: config.base + "warehouse/warehouse/admin/productVariety/list",
            data: [],
            cols: [
                [
                    {field: "varietyName", align: "center", title: "业务项目"},
                    {field: "warehouseContractPrice", align: "center", title: "标准价"},
                    {field: "memberPrice", align: "center", title: "会员价"},
                    {
                        field: "newContractPrice", align: "center", title: "合同价格",
                        templet: admin.setTableInput("newContractPrice", nowData.eventName === "detail", "newContractPrice")
                    },
                ]
            ],
            done: function () {
                admin.tableInputChangeByClass("custodyFeesFormTable", "newContractPrice");
            },
            parseData: function (res) {

            },
        });

        if (nowData.eventName === "detail") {
            $("#continto").show();
            $("#settledDetailContentForm .layui-table-cell").css("overflow", "hidden ");
            admin.setFormDisable("#settledDetailContentForm", true);
        } else {
            const feeItemsList = await admin.reqPro('warehouse/warehouse/feeItems/list', {});
            const VarietyList = await admin.reqPro('warehouse/warehouse/admin/productVariety/list', {});
            feeItemsList.data.map(item => {
                if (item.price === '' || item.price === undefined) {
                    item.contractPrice = item.price = 0
                } else if (item.price === 0) {
                    item.contractPrice = '0'
                } else if (item.price !== 0 && item.price !== '') {
                    item.contractPrice = item.price
                }
                item.memberPrice = 0
            })
            VarietyList.data.map(item => {
                item.warehouseContractPrice = item.contractPrice
                if (item.contractPrice === '' || item.contractPrice === undefined) {
                    item.newContractPrice = item.contractPrice = 0
                } else if (item.contractPrice === 0) {
                    item.newContractPrice = '0'
                } else if (item.contractPrice !== 0 && item.contractPrice !== '') {
                    item.newContractPrice = item.contractPrice
                }
            })
            console.log(VarietyList, "VarietyList")
            const feeItemsCont = feeItemsList.data
            const VarietyCont = VarietyList.data
            tableVal.reload({
                data: feeItemsCont
            });
            VarietyVal.reload({
                data: VarietyCont
            });
        }

        if (data && data[0].id) {

            // form.val("settledDetailContent", data[0]);
            console.log(data[0].warehouseContractFeeVOList, "22222")
            if (data[0].warehouseContractFeeVOList != undefined) {
                tableVal.reload({
                    data: data[0].warehouseContractFeeVOList.map(v => {
                        delete v.length
                        return v
                    }),
                });
            }
            if (data[0].warehouseContractProductVOList != undefined) {
                VarietyVal.reload({
                    data: data[0].warehouseContractProductVOList.map(v => {
                        v.newContractPrice = v.contractPrice
                        // v.markName = v.varietyName
                        delete v.length
                        return v
                    })
                });
            }


        } else {
            console.log(111111)

        }
        console.log(data, "-----data-------data")
        form.on("submit(formSubmit)", function (d) {
            let formData = {}
            let settledId = nowData.data[0].id
            let warehouseCustomerId = nowData.data[0].warehouseCustomerId
            let contactId = nowData.data[0].contactId
            console.log(settledStatus, "settledStatus")
            if (settledStatus == '') {
                layer.msg("请选择审核结果", {icon: 2, time: 1000});
                return false;
            } else if (settledStatus == 1) {
                let processForm = table.cache["processFormTable"];
                formData = {settledStatus, warehouseCustomerId, contactId, settledId, ...processForm[0]};
                formData.type = 1
                formData.warehouseFeeItemsList = table.cache["serviceProductsFormTable"]
                formData.warehouseProductVarietyList = table.cache["custodyFeesFormTable"]
                formData.warehouseFeeItemsList.map(item => {
                    item.price = item.contractPrice
                })
                formData.warehouseProductVarietyList.map(item => {
                    item.contractPrice = Number(item.newContractPrice)
                })
                console.log(formData, "formData")
                if (formData.contractCode === '') {
                    layer.msg("请填写合同编号", {icon: 2, time: 1000});
                    return false;
                }
                if (formData.contractName === '') {
                    layer.msg("请填写合同名称", {icon: 2, time: 1000});
                    return false;
                }
                if (formData.contractCategoryId === '') {
                    layer.msg("请选择合同分类", {icon: 2, time: 1000});
                    return false;
                }
                if (formData.warehouseUserId === '') {
                    layer.msg("请选择客户签约人", {icon: 2, time: 1000});
                    return false;
                }
                if (formData.contractorId === '') {
                    layer.msg("请选择我方签约人", {icon: 2, time: 1000});
                    return false;
                }
                if (formData.effectiveDate === '') {
                    layer.msg("请选择合同生效日期", {icon: 2, time: 1000});
                    return false;
                }
                if (formData.expiryDate === '') {
                    layer.msg("请选择合同有效截止日期", {icon: 2, time: 1000});
                    return false;
                }
                if (formData.warehouseFeeItemsList.some(item => item.price === ''  || Number(item.price) < 0)) {
                    layer.msg("请填写服务产品合同价格", {icon: 2, time: 1000});
                    return false;
                }

                if (formData.warehouseProductVarietyList.some(item => item.contractPrice === ''  || Number(item.contractPrice) < 0)) {
                    layer.msg("请填写托管费用合同价格", {icon: 2, time: 1000});
                    return false;
                }
                admin.req(
                    "warehouse/warehouse/settled/examine",
                    JSON.stringify(formData),
                    function (res) {
                        layer.closeAll("loading");
                        if (res.code == 200) {
                            layer.msg(res.msg, {icon: 1});
                            table.reload('warehouseOrderTable');
                            layer.closeAll("page");
                        } else {
                            layer.msg(res.msg, {icon: 2, time: 1000});
                        }
                    },
                    "POST",
                    false,
                    "application/json"
                );
            } else if (settledStatus == 2) {
                admin.req('warehouse/warehouse/settled/revoke', {
                    status: settledStatus,
                    id: settledId
                }, function (data) {
                    layer.closeAll('loading');
                    if (data.code == 200) {
                        layer.msg(data.msg, {icon: 1});
                        table.reload('warehouseOrderTable');
                        layer.closeAll("page");
                    } else {
                        layer.msg(data.msg, {icon: 2});
                    }
                }, 'GET');
            }
        });

        $("#settledDetailContentForm .layui-table-body").css("overflow", "visible");
        $("#settledDetailContentForm .layui-table-box").css("overflow", "visible");
        $("#settledDetailContentForm .layui-table-view").css("overflow", "visible");
    });
</script>

<style>

    #settledDetailContentForm .layui-form-label {
        width: 125px;
    }

    #settledDetailContentForm .layui-input-block {
        margin-left: 155px;
    }

    #settledDetailContentForm .layui-form-item .layui-inline {
        /* margin-bottom: 5px; */
        margin-right: 0px;
    }

    #settledDetailContentForm .layui-table-cell {
        overflow: visible;
    }

    #settledDetailContentForm .layui-table-box {
        overflow: visible !important;
    }

    #settledDetailContentForm .layui-table-body {
        overflow: visible !important;
    }

    #continto .layui-table-box {
        overflow: hidden !important;
    }

    #continto .layui-table-body {
        overflow: auto !important;
    }

    .chooseCode {
        position: relative;
    }

    .mask {
        position: absolute;
        width: 100%;
        height: 100%;
        background: rgba(158, 157, 157, 0.1);
        top: 50%;
        left: 50%;
        z-index: 2;
        transform: translate(-50%, -50%);
    }

</style>